from peewee import *
from api.utils import get_uuid
from datetime import datetime
from api.db.db_models import DB, DataBaseModel

class Document(DataBaseModel):
    id = CharField(primary_key=True)
    create_time = BigIntegerField(null=True, index=True)
    create_date = DateTimeField(null=True, index=True)
    update_time = BigIntegerField(null=True, index=True)
    update_date = DateTimeField(null=True, index=True)
    thumbnail = TextField(null=True)
    kb_id = CharField(max_length=256, index=True)
    parser_id = CharField(max_length=32, index=True)
    parser_config = TextField()
    source_type = CharField(max_length=128, index=True)
    type = CharField(max_length=32, index=True)
    created_by = CharField(max_length=32, index=True)
    name = CharField(max_length=255, null=True, index=True)
    location = CharField(max_length=255, null=True, index=True)
    size = IntegerField(index=True)
    token_num = IntegerField(index=True)
    chunk_num = IntegerField(index=True)
    progress = FloatField(index=True)
    progress_msg = TextField(null=True)
    process_begin_at = DateTimeField(null=True, index=True)
    process_duation = FloatField()
    meta_fields = TextField(null=True)
    run = CharField(max_length=1, null=True, index=True)
    status = CharField(max_length=1, null=True, index=True)
    oss_url = CharField(max_length=512, null=True, index=True)
    video_id = CharField(max_length=64, null=True, index=True)

    class Meta:
        db_table = 'document'

class knowledgebase(DataBaseModel):
    id = CharField(primary_key=True)
    name=CharField(max_length=255, null=True, index=True)
    created_by = CharField(max_length=32, null=True, index=True)

class User(DataBaseModel):
    id = CharField(primary_key=True)
    email=CharField(max_length=255, null=True, index=True)
    
class DocumentService:
    @classmethod
    @DB.connection_context()
    def get_documents(cls, kb_id=None, name=None, start_date=None, end_date=None, 
                    order_by='date', page=1, page_size=10):
        """获取文档列表
        
        Args:
            kb_id: 精确匹配知识库ID
            name: 模糊匹配文档名称
            start_date: 开始日期
            end_date: 结束日期
            order_by: 排序方式 ('name' 或 'date')
            page: 页码
            page_size: 每页数量
        """
        query = Document.select()
        
        # 精确匹配知识库ID
        if kb_id:
            query = query.where(Document.kb_id == kb_id)
        
        # 模糊匹配文档名称
        if name:
            query = query.where(Document.name.contains(name))
        
        # 时间范围筛选
        if start_date:
            query = query.where(Document.create_date >= start_date)
        if end_date:
            query = query.where(Document.create_date <= end_date)
            
        # 排序
        if order_by == 'name':
            query = query.order_by(Document.name.asc())
        else:  # 默认按创建日期降序
            query = query.order_by(Document.create_date.desc())
            
        # 分页
        total = query.count()
        documents = query.paginate(page, page_size).dicts()
        
        return {
            'list': list(documents),
            'total': total,
            'page': page,
            'page_size': page_size
        }

    @classmethod
    @DB.connection_context()
    def get_knowledgebases_by_email(cls, email):
        """通过邮箱获取用户的所有知识库
        
        Args:
            email: 用户邮箱
            
        Returns:
            list: 知识库列表 [{'id': 'kb1', 'name': '知识库1'}, ...]
            
        Raises:
            ValueError: 用户不存在
            Exception: 其他错误
        """
        try:
            # 1. 通过邮箱查询用户
            user = User.get(User.email == email)
            
            # 2. 查询该用户创建的所有知识库
            kbs = (knowledgebase
                .select(knowledgebase.id, knowledgebase.name)
                .where(knowledgebase.created_by == user.id)
                .dicts())
                
            return list(kbs)
            
        except DoesNotExist:
            raise ValueError("User not found with this email")
        except Exception as e:
            raise Exception(f"Failed to get knowledgebases: {str(e)}")

    @classmethod
    @DB.connection_context()
    def update_document_resources(cls, document_id, oss_url=None, video_id=None):
        """更新文档资源链接"""
        update_fields = {}
        if oss_url is not None:
            update_fields['oss_url'] = oss_url
        if video_id is not None:
            update_fields['video_id'] = video_id
            
        if not update_fields:
            return False
            
        update_fields['update_time'] = int(datetime.now().timestamp())
        update_fields['update_date'] = datetime.now()
        
        return Document.update(**update_fields).where(Document.id == document_id).execute()

    @classmethod
    @DB.connection_context()
    def get_document_by_id(cls, document_id):
        """根据ID获取单个文档"""
        try:
            return Document.get(Document.id == document_id)
        except DoesNotExist:
            return None
        
    